package com.heima.article.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ArticleConfigMapper;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.constants.WmNewsMessageConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;
@Component
@Slf4j
public class DownOrUpListener {

    @Autowired
    private ArticleConfigMapper articleConfigMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /*
    监听文章上下架功能
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_QUEUE, durable = "true"),
                    exchange = @Exchange(name = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, type = ExchangeTypes.TOPIC),
                    key = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_ROUTINGKEY
            )
    )
    public void getMessage(String message) {
        String[] messagesplit = message.split(",");

        Long articleId = Long.valueOf(messagesplit[0]);

        Boolean isDown;
        if ("1".equals(messagesplit[1])) {
            isDown = false;
        } else {
            isDown = true;
        }

        ApArticleConfig apArticleConfig = articleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, articleId));
        apArticleConfig.setIsDown(isDown);

        articleConfigMapper.update(apArticleConfig, Wrappers.<ApArticleConfig>lambdaUpdate().eq(ApArticleConfig::getArticleId, articleId));

        if (isDown == false) {
            //生成rabbitmq唯一消息码
            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());

            rabbitTemplate.convertAndSend(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, ArticleConstants.ARTICLE_ES_SYNC_ROUTINGKEY, articleId, correlationData);
        }
    }
}
